import Api from './api';
import { ListGUID } from './ListGuid';

export default class indexDb {

  

    // 创建数据库  databaseName 数据库名称 version 版本号
    public static async InitContactIndexDb(tableName=''
    ): Promise<any> {
        try {
            //open
            let request = window.indexedDB.open("SUMIKAContract", 1);
            var dataTableList = ['Petition','StandingBook', 'RegulationsLib','ContractPetitionLib','RegulationsPetitionLib','CommonLib','ContractLib'];
            if(tableName!=''){
                dataTableList=[tableName];
            }
            //初始化
            request.onupgradeneeded = function (event: any) {
                var db = event.target.result;
                
                dataTableList.forEach(async e => {
                    await InitTableData(db, e);
                })

                dataTableList.forEach(async e => {
                     AddTableData(db,e);
                })

            };
            request.onsuccess = function (e) {
                var db = request.result;
                //数据更新
                dataTableList.forEach(async e => {
                    await InitTableData(db, e);
                })
               
                dataTableList.forEach(async e => {
                     AddTableData(db,e);
                })

               
            }

            request.onerror = function (e) {
               
            }


        } catch (e) {
            
        }
    }


    

    // 读取数据，入参是tablename
    public static async getTableData(tableName
    ): Promise<any> {

        try {
            //重新open
            //transcation, read
            //先要检查这个table存在不在存在，如果存在直接读取，如果不存在要通过pnpjs获取到数据然后push到表
            //close
            //return 数据，也是一个数组
            // return
            let request =await window.indexedDB.open("SUMIKAContract", 1);
            // await sleep(2000);
            request.onsuccess = function (event) {
                var db = request.result;
                if (db) {
                    var transaction = db.transaction([tableName]);
                    var objectStore = transaction.objectStore(tableName);
                    var datalist= objectStore.getAll();
                    datalist.onsuccess=function(res:any){
                        var r=res.target.result;
                        return r;
                    }
                    //这要异步刷新数据 todo
                  
                } else {
                    
                }
            };

        } catch (e) {
            
        }


    }



}

async function InitTableData(db: any, dbName: string) {
    try {

        // 判断有没有表 没有表开始创建
        var isExistTable = false;
        if (!db.objectStoreNames.contains(dbName)) {
            var objectStore = await db.createObjectStore(dbName, { autoIncrement: true });
            objectStore.createIndex('id', 'id', { unique: true });
            //  objectStore.transaction.oncomplete = async (event) => {
            //     
            //     // 表名称  + 读写方式
            //     var customerObjectStore = db.transaction([dbName], 'readwrite')
            //         .objectStore(dbName);
            //      await   AddTableData(customerObjectStore,dbName);

            // };
        } else {
            //     isExistTable = true;
                //更新数据，先临时对表的数据进行清除，然后再全量的添加数据
                var transaction = db.transaction([dbName], 'readwrite');
                var objectStore = transaction.objectStore(dbName);
                objectStore.clear();
            //    await AddTableData(objectStore,dbName);
        }


    } catch (e) {
        
    }
}



async function AddTableData(db: any, dbName: string) {
    try {
        var spListGuid = '';
        if (dbName == 'Petition') {
            spListGuid = ListGUID.Petition;
        } else if (dbName == 'StandingBook') {
            spListGuid = ListGUID.StandingBook;
        }

        if (spListGuid != '') {
            let array = {
                Guid: spListGuid
            }
            
            //通过API获取到数据 Pngjs
            // var dataList = await Api._getPagedFromPS(array);
            
            // dataList.forEach(element => {
            //     var customerObjectStore = db.transaction([dbName], 'readwrite').objectStore(dbName);
            //     var addRequest= customerObjectStore.add(element);
            //     addRequest.onerror=function(e){
            //         
            //     }
            //     addRequest.onsuccess =function(e){
    
            //     }
            // });
            
        }


    } catch (e) {
        
    }
}

